package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        //打印错误日志
        log.error(exception .getMessage());
        //判断错误里面包含Duplicate entry 包含的话给出准确信息 用空格切割出来并存入数组
        if (exception.getMessage().contains("Duplicate entry")){
            String[] split= exception.getMessage().split(" ");
            String msg =split[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误，新增失败");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        //打印错误日志
       log.error(ex.getMessage());
       return R.error(ex.getMessage());
    }
}
